import os
import json
import re
from dotenv import load_dotenv  # 新增导入

# 加载.env文件中的环境变量
load_dotenv()  # 新增

# 从环境变量中获取基础路径
base_html_path = os.getenv('angularjs-project-path')  # 修改
base_output_path = os.getenv('vue-project-path')  # 修改
# 验证路径是否存在
if not base_html_path or not base_output_path:
    raise ValueError("请在.env文件中配置BASE_HTML_PATH和BASE_OUTPUT_PATH")

# 获取用户输入的目标节点ID
target_id = input("请输入要查找的目标菜单Name: ")  # 用户输入目标节点ID

def find_controller_in_js(js_path, controller_name):
    """在JS文件中查找控制器函数定义（改进版）"""
    try:
        with open(js_path, 'r', encoding='utf-8') as f:
            content = f.read()

        # 改进1：更灵活的函数匹配模式
        # 处理: function name(...) { 或 name: function(...) { 或 app.controller('name', ...
        patterns = [
            # 标准函数定义
            rf'function\s+{re.escape(controller_name)}\s*\([^)]*\)\s*\{{',
            # AngularJS 的 .controller 注册
            rf'\.controller\s*\(\s*[\'"]{re.escape(controller_name)}[\'"]\s*,\s*function\s*\(',
            # 对象方法定义
            rf'{re.escape(controller_name)}\s*:\s*function\s*\('
        ]

        for pattern in patterns:
            start_match = re.search(pattern, content, re.DOTALL)
            if start_match:
                start_pos = start_match.start()

                # 改进2：更好的大括号匹配（处理嵌套）
                brace_count = 0
                end_pos = start_pos
                in_string = False
                string_char = None
                escape = False

                for i, c in enumerate(content[start_pos:]):
                    if escape:
                        escape = False
                        continue

                    if c == '\\':
                        escape = True
                        continue

                    if in_string:
                        if c == string_char:
                            in_string = False
                        continue

                    if c in ('"', "'"):
                        in_string = True
                        string_char = c
                        continue

                    if not in_string:
                        if c == '{':
                            brace_count += 1
                        elif c == '}':
                            brace_count -= 1
                            if brace_count == 0:
                                end_pos = start_pos + i + 1
                                return content[start_pos:end_pos]

                # 如果没找到结束大括号，返回整个匹配部分
                return content[start_pos:]

        return None
    except Exception as e:
        print(f"Error reading {js_path}: {str(e)}")
        return None

def process_node(node, parent_path=""):
    """递归处理每个节点"""
    # 1. 查找目标节点
    if node.get('name') == target_id:
        process_target_node(node)
        return True

    # 递归处理子节点
    for child in node.get('children', []):
        if process_node(child, parent_path):
            return True
    return False

def process_target_node(node):
    """处理目标节点"""
    # 获取元数据
    meta = node.get('meta', {})
    component_path = node.get('component', '')

    # 2. 处理主组件
    # 构建输出路径
    output_file = os.path.join(base_output_path, f"{component_path}.vue".replace('//', '/'))
    os.makedirs(os.path.dirname(output_file), exist_ok=True)

    # 3. 处理HTML和JS
    html_relative = meta.get('htmlUrl', '')
    js_files = meta.get('fileJs', [])

    if html_relative:
        process_html_and_js(html_relative, js_files, output_file)

    # 4. 处理dialogService.page调用
    process_dialog_calls(node, js_files, output_file)

def process_html_and_js(html_relative, js_files, output_file):
    """处理HTML和关联的JS文件"""
    # 构建完整路径
    html_path = os.path.join(base_html_path, html_relative)

    # 读取HTML内容
    try:
        with open(html_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
    except FileNotFoundError:
        print(f"HTML文件未找到: {html_path}")
        return

    # 查找控制器名称
    controller_match = re.search(r'(?:data-)?ng-controller="([^"]+)"', html_content)
    if not controller_match:
        print(f"在 {html_path} 中未找到ng-controller")
        return

    controller_name = controller_match.group(1)
    print(f"找到控制器: {controller_name}")

    # 在JS文件中查找控制器
    js_code = ""
    for js_rel in js_files:
        js_path = os.path.join(base_html_path, js_rel)
        code = find_controller_in_js(js_path, controller_name)
        if code:
            js_code = code
            break

    if not js_code:
        print(f"在JS文件{js_path}中未找到控制器: {controller_name}")
        return

    # 生成Vue组件
    vue_template = f"""<template>
{html_content}
</template>

<script>
{js_code}
</script>
"""
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(vue_template)
    print(f"生成主组件: {output_file}")

def process_dialog_calls(node, js_files, parent_output):
    """处理dialogService.page调用"""
    for js_rel in js_files:
        js_path = os.path.join(base_html_path, js_rel)
        try:
            with open(js_path, 'r', encoding='utf-8') as f:
                js_content = f.read()
        except FileNotFoundError:
            continue

        # 查找所有dialogService.page调用
        pattern = r'dialogService\.(?:page|sidebar)\("([^"]+)",\s*{'

        matches = re.finditer(pattern, js_content)
        for match in matches:
            alias = match.group(1)
            print(f"找到dialog调用: {alias}")

            # print(f"node: {node}")
            # 在subPages中查找匹配项
            subpage = find_subpage_by_alias(node, alias)
            # print(f"subpage: {subpage}")
            if subpage:
                process_subpage(subpage, parent_output)

def find_subpage_by_alias(node, alias):
    """在当前节点的meta.subPages中查找匹配的alias，处理alias格式"""
    # 直接从当前节点的meta中获取subPages
    subpages = node.get('meta', {}).get('subPages', [])
    for sub in subpages:
        sub_alias = sub.get('alias', '')
        # 处理alias：去掉system.前缀，将_替换为.
        processed_alias = sub_alias.replace('system.', '').replace('_', '.')
        # 比较处理后的alias
        if processed_alias == alias:
            return sub
    return None

def process_subpage(subpage, parent_output):
    """处理子页面"""
    html_relative = subpage.get('htmlUrl', '')
    js_files = subpage.get('fileJs', [])

    # 构建输出路径
    output_dir = os.path.join(os.path.dirname(parent_output), 'dlg')
    os.makedirs(output_dir, exist_ok=True)

    # 从HTML路径获取文件名
    base_name = os.path.splitext(os.path.basename(html_relative))[0]
    output_file = os.path.join(output_dir, f"{base_name}.vue")

    process_html_and_js(html_relative, js_files, output_file)

if __name__ == "__main__":
    # 加载JSON数据
    with open('data.json', 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 开始处理
    for item in data:
        if process_node(item):
            break
    else:
        print("未找到目标节点")
